﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using BrewXML.Core.Data;
using BrewXML.Core.Services.NavigationServices;
using BrewXML.Core.ViewModels;
using BrewXML.WindowsPhone.Data;
using Cirrious.CrossCore;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Venetasoft.WP.Net;

namespace BrewXML.WindowsPhone
{
    public partial class RecipeDetailPage : PhoneApplicationPage
    {
        #region View Model
        public RecipeDetailPageViewModel ViewModel
        {
            get
            {
                return this.DataContext as RecipeDetailPageViewModel;
            }
        }
        #endregion

        #region OnNavigateTo

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //// init();
            //this.StyleListPicker.SelectedItems.Clear();
            base.OnNavigatedTo(e);
        }
        #endregion
        public void init()
        {
            var list = XMLClass.Load<List<STYLE>>("Styles.xml", "STYLES");
            ViewModel.ListStyle = list.Result;
            //if (!ViewModel.AllowAdd) ViewModel.Style = ViewModel.RECIPE.STYLE;
            var list1 = XMLClass.Load<List<GRAIN>>("Grains.xml", "GRAINS");
            ViewModel.ListGrainPicked = list1.Result;
            
            var list2 = XMLClass.Load<List<HOP>>("Hops.xml", "HOPS");
            ViewModel.ListHopPicked = list2.Result;
            
            var list3 = XMLClass.Load<List<MISC>>("Miscs.xml", "MISCS");
            ViewModel.ListMiscPicked = list3.Result;
            
        }

        #region Build Application Bar
        private void BuildApplicationBar()
        {
            
            var appBar = new ApplicationBar() { Opacity = 1, Mode = ApplicationBarMode.Default };
            var btnAdd = new ApplicationBarIconButton(new Uri("/Asset/save.png", UriKind.Relative)) { Text = "Save" };
            btnAdd.Click += (sender, args) =>
            {

                if (!ViewModel.AllowAdd)
                {
                    ViewModel.RECIPE.STYLE = ViewModel.Style;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES.Save("Recipes.xml", "RECIPES");
                    var ttt = Mvx.Resolve<RecipesPageViewModel>().RECIPES;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES = null;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES = ttt;
                }
                else
                {
                    ViewModel.RECIPE.STYLE = ViewModel.Style;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES.Add(ViewModel.RECIPE);
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES.Save("Recipes.xml", "RECIPES");
                    var ttt = Mvx.Resolve<RecipesPageViewModel>().RECIPES;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES = null;
                    Mvx.Resolve<RecipesPageViewModel>().RECIPES = ttt;
                    ViewModel.AllowAdd = false;
                }
            };
            appBar.Buttons.Add(btnAdd);

            var btndelete = new ApplicationBarIconButton(new Uri("/Asset/delete.png", UriKind.Relative)) { Text = "Delete" };
            btndelete.Click += (sender, args) =>
            {
                int index = Mvx.Resolve<RecipesPageViewModel>().RECIPES.IndexOf(ViewModel.RECIPE);
                Mvx.Resolve<RecipesPageViewModel>().RECIPES.RemoveAt(index);
                Mvx.Resolve<RecipesPageViewModel>().RECIPES.Save("Recipes.xml", "RECIPES");
                var ttt = Mvx.Resolve<RecipesPageViewModel>().RECIPES;
                Mvx.Resolve<RecipesPageViewModel>().RECIPES = null;
                Mvx.Resolve<RecipesPageViewModel>().RECIPES = ttt;
                Mvx.Resolve<INavigationService>().GoBack();
            };
            appBar.Buttons.Add(btndelete);
            var btnShare = new ApplicationBarIconButton(new Uri("/Asset/share.png", UriKind.Relative)) { Text = "Share" };
            btnShare.Click += (sender, args) =>
            {
                //this.GerenateHtml();
                this.MailPopup.IsOpen = true;
                this.ContentPanel.Visibility = Visibility.Collapsed;
            };
            appBar.Buttons.Add(btnShare);
            if (ViewModel.AllowAdd)
            {
                btnShare.IsEnabled = false;
                btndelete.IsEnabled = false;
            }
            else
            {
                btnShare.IsEnabled = true;
                btndelete.IsEnabled = true;
            }
            this.ApplicationBar = appBar;
        }
        #endregion
        public RecipeDetailPage()
        {
            
            InitializeComponent();
            BuildApplicationBar();
            init();
        }
        private void Liter_OnLostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            if (!textBox.Text.Contains("lit"))
                textBox.Text = string.Format("{0} lit", textBox.Text);
        }

        private void KG_OnLostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            if (!textBox.Text.Contains("kg"))
                textBox.Text = string.Format("{0} kg", textBox.Text);
            
        }
        private void Min_OnLostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            if (!textBox.Text.Contains("min"))
                textBox.Text = string.Format("{0} min", textBox.Text);
        }

        public void WriteData(string filename, string content)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.DeleteFile(filename);
                using (var steam = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, store))
                {
                    using (var writer = new StreamWriter(steam))
                    {
                        writer.Write(content);
                    }
                }
            }
        }

        public void GerenateHtml()
        {
            if (ViewModel.RECIPE != null)
            {
                //Generate html
                StringBuilder mailbody = new StringBuilder();
                mailbody.AppendFormat("<html>");
                mailbody.AppendFormat("<head>");
                mailbody.AppendFormat(
                    "<meta charset=utf-8><meta http-equiv=Content-Type content=text/html; charset=UTF-8 />");
                mailbody.AppendFormat("<style type=text/css>");

                string s = "<!--#content{width: 75%;margin: 0 auto}table {border-collapse: collapse;border-spacing: 0px;*border-collapse: expression('separate', cellSpacing = '0px');width: 100%;}tr.titleRow {background-color: #CCC;}tr.dataRow {background-color: #FFF;}td.majorTitleCell {background-color: #CCC;text-align: center;vertical-align: middle;}td.titleCell {background-color: #CCC;vertical-align: top;}td.dataCell {background-color: #FFF;}-->";
                mailbody.AppendLine(s);
                mailbody.AppendFormat("</style>");

                mailbody.AppendFormat("</head>");
                mailbody.AppendFormat("<body>");
                mailbody.AppendFormat("<div id=content>");
                mailbody.AppendFormat("<h2>{0}</h2>",ViewModel.RECIPE.NAME);
                mailbody.AppendFormat("<table>");
                mailbody.AppendFormat("<tr class=titleRow><td class=titleCell><b><font size=3>Brewer Name</font></font></b></td></tr>");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell>{0}</td></tr>",ViewModel.RECIPE.BREWER);
                mailbody.AppendFormat("<tr class=titleRow><td class=titleCell><b><font size=3>Style</font></font></b></td></tr>");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell>{0}</td></tr>", ViewModel.RECIPE.STYLE.NAME);
                mailbody.AppendFormat("<tr class=titleRow><td class=titleCell><b><font size=3>Detail</font></font></b></td></tr>");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>Batch size</b></span><span style='margin-left:68px;'>{0}</span></td></tr>", ViewModel.RECIPE.BATCH_SIZE+" lit");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "OG        ",ViewModel.RECIPE.OG);
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "FG        ", ViewModel.RECIPE.FG);
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "IBU       ", ViewModel.RECIPE.IBU);
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "COLOR     ", ViewModel.RECIPE.COLOR + " srm");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "ABV       ", ViewModel.RECIPE.ABV + " %");
                mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", "ABW       ", ViewModel.RECIPE.ABW + " %");
                mailbody.AppendFormat("<tr class=titleRow><td class=titleCell><b><font size=3>Grains</font></font></b></td></tr>");
                foreach (var item in ViewModel.RECIPE.GRAINS)
                {
                    mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", item.NAME, item.AMOUNT + " kg");
                }
                mailbody.AppendFormat("<tr class=titleRow><td class=titleCell><b><font size=3>Hops</font></font></b></td></tr>");
                foreach (var item in ViewModel.RECIPE.HOPS)
                {
                    mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span><span style='padding-left:68px;'>{2}</span></td></tr>", item.NAME, item.AMOUNT + " kg", item.TIME + " min");
                }
                foreach (var item in ViewModel.RECIPE.MISCS)
                {
                    mailbody.AppendFormat("<tr class=dataRow><td class=dataCell><span><b>{0}</b></span><span style='margin-left:68px;'>{1}</span></td></tr>", item.NAME, item.AMOUNT + " kg");
                }
                mailbody.AppendFormat("</table>");
                mailbody.AppendFormat("</div>");
                mailbody.AppendFormat("</body>");
                mailbody.AppendFormat("</html>");
                WriteData(string.Format("Recipe {0}.html",ViewModel.RECIPE.NAME), mailbody.ToString());
            }
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            GerenateHtml();
            MailMessage mailMessage = new MailMessage();
            mailMessage.MailSent += mailMessage_MailSent;
            mailMessage.Progress += mailMessage_Progress;
            //set account
            mailMessage.UserName = this.txtUserName.Text.Trim();
            mailMessage.Password = this.txtPass.Password;
            if (mailMessage.UserName.Contains("@gmail"))
                mailMessage.AccountType = MailMessage.AccountTypeEnum.Gmail;
            else if (mailMessage.UserName.Contains("@live"))
                mailMessage.AccountType = MailMessage.AccountTypeEnum.MicrosoftAccount;
            //set emaildata
            mailMessage.To = this.txtToEmail.Text.Trim();
            mailMessage.Subject = "BeerXML Recipe";
            mailMessage.Body = "";
            //attachment
            string tmp = string.Format("Recipe {0}.html", ViewModel.RECIPE.NAME);
            mailMessage.AddAttachment(tmp);
            mailMessage.Send();
        }
        void mailMessage_Progress(object sender, Venetasoft.WP7.ValueEventArgs<int> e)
        {
            try
            {
                this.txtProgress.Text = "Sending " ;
            }
            catch (Exception)
            {


            }

        }

        void mailMessage_MailSent(object sender, Venetasoft.WP7.ValueEventArgs<bool> e)
        {
            if (e.Value == false)   //mail not sent         
            {
                this.txtProgress.Text = "Mail not sent";
            }
            else
            {
               // this.txtProgress.Text = "Successfully";
                this.ApplicationBar.IsVisible = true;
                MailPopup.IsOpen = false;
                this.ContentPanel.Visibility = Visibility.Visible;
            }
        }
        private void ButtonCancel_OnClick(object sender, RoutedEventArgs e)
        {
            this.MailPopup.IsOpen = false;
            this.ContentPanel.Visibility = Visibility.Visible;
        }
    }
}